package todo;

import se.lth.cs.realtime.*;
import se.lth.cs.realtime.event.*;
import done.*;

public class WashingController implements ButtonListener {
	private AbstractWashingMachine theMachine;
	private double theSpeed;
	TemperatureController tc;
	WaterController wc;
	SpinController sc;
	WashingProgram wp;
	boolean forceProg3;

	private final long tcPeriod = 10000;
	private final long wcPeriod = 1000;
	private final long scPeriod = 1000;

	public WashingController(AbstractWashingMachine theMachine, double theSpeed) {
		this.theMachine = theMachine;
		this.theSpeed = theSpeed;

		tc = new TemperatureController(theMachine, (long) (tcPeriod / theSpeed));
		wc = new WaterController(theMachine, (long) (wcPeriod / theSpeed));
		sc = new SpinController(theMachine, (long) (scPeriod / theSpeed));
		tc.start();
		wc.start();
		sc.start();

		wp = null;
	}

	public void processButton(int theButton) {
		switch (theButton) {
		case 0: // if washing is interrupted, run program3
			wp.interrupt();
			forceProg3 = true;
			break;
		case 1: // if lock is open, run program1
			if (!theMachine.isLocked()) {
				wp = new WashingProgram1(theMachine, theSpeed, tc, wc, sc);
				wp.start();
			}
			break;
		case 2: // if lock is open, run program2
			if (!theMachine.isLocked()) {
				wp = new WashingProgram2(theMachine, theSpeed, tc, wc, sc);
				wp.start();
			}
			break;
		case 3: // if power failure or interrupt has occurred, run program3
			if (wp == null || forceProg3) {
				wp = new WashingProgram3(theMachine, theSpeed, tc, wc, sc);
				wp.start();
			}
			break;
		}
	}
}
